<template>
  <el-form-item class="match-form-item">
    <el-row :gutter="20">
      <!-- 默认项 -->
      <el-col class="btn-match-wrapper" :span="6" v-for="item in DEFAULT_ITEMS" :key="item">
        <el-button disabled> {{item}} </el-button>
      </el-col>
      <template v-if="editorValues && editorValues.length">
        <el-col class="btn-match-wrapper" :span="6" v-for="(item, index) in editorValues" :key="item.key">
          <el-button
            @click="handleEditValues(item, index)">
            {{item.fieldText}}
          </el-button>
          <i class="el-icon-circle-close match-delete-icon" @click="handleDelValue(index)"></i>
        </el-col>
      </template>
      <el-col class="btn-match-wrapper" :span="6">
        <el-button icon="plus" @click="toggleShowDialog('add')" :disabled="addBtnDisabled"></el-button>
      </el-col>
    </el-row>
    <el-dialog
      size="tiny"
      :visible.sync="newDialogState"
      :title="msgTitle"
      custom-class="match-dialog-wrapper">
      <el-form :model="form" :rules="rules" label-width="142px" ref="form" v-bind="getFormProps()">
        <el-form-item
          prop="fieldText"
          :rules="[
            { required: !0, message: '请输入用户报名填写项'},
            Object.assign({}, validatorObj)
          ]">
          <el-input v-model="form.fieldText" :maxlength="8" placeholder="输入用户报名填写项"/>
        </el-form-item>
        <el-form-item
          prop="listItems"
          :rules="[
            { required: !1},
            Object.assign({}, validatorObj, {trigger: 'blur'})
          ]">
          <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="填写候选项，让报名者能够直接点选" name="1">
              <div class="tips">候选项只能单选</div>
              <!-- 显示隐藏强制重绘文本框组 防止数据不更新 -->
              <el-scrollbar>
                <e-input-group
                  v-if="newDialogState"
                  :style="{
                    'height': form.listItems.length > 4 ? '240px' : 'auto'
                  }"
                  placeholder="输入候选项"
                  :max-item="50" :maxlength="8" v-model="form.listItems" />
              </el-scrollbar>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toggleShowDialog()">取 消</el-button>
        <el-button type="primary" @click="handleSave()">确 定</el-button>
      </div>
    </el-dialog>
  </el-form-item>
</template>
<script>
  /**
  * 输入{values}
  * 输出{values, result}
  */
  import EInputGroup from '@e-ui/InputGroup'

  import {form} from 'utils/mixins' // 引入form mixin
  const DEFAULT_ITEMS = ['真实姓名', '性别', '手机', '证件号码', '出生日期']
  export default {
    mixins: [form],
    components: {
      EInputGroup
    },
    props: {
      value: {
        type: Object
      }
    },
    computed: {
      addBtnDisabled () {
        return Boolean(this.editorValues && this.editorValues.length >= 20)
      }
    },
    watch: {
      newDialogState (newVl) {
        // 隐藏 则重置表单
        if (!newVl) {
          this.resetFormData()
        }
      }
    },
    mounted () {
      let that = this
      this._defaultValue()
      // 填写项 候选项验证规则
      this.validatorObj = {
        validator (rule, value, callback) {
          if (typeof value === 'string') {
            value = (value || '').trim() // 默认值设置
            let exitIndex = that.editorValues.findIndex(k => k.fieldText === value)
            if (exitIndex !== -1 && exitIndex !== that.$curIndex) {
              callback(new Error(this.message1))
            }
          } else {
            value = value || [] // 默认值设置
            let tempArr = []
            let regRule = /^[\u4e00-\u9fa5a-zA-Z0-9@]*$/ // 中英数 + @ 限制
            value.forEach((item = '', index) => {
              item = item.trim() // 去空格
              if (item && tempArr.includes(item)) {
                callback(new Error(this.message2))
                return !1
              } else if (item && !regRule.test(item)) {
                callback(new Error(this.message3))
                return !1
              } else {
                tempArr.push(item)
              }
              return tempArr
            })
          }
          callback()
        },
        message1: '填写项不能出现同名',
        message2: '候选项不能出现同名',
        message3: '内容只能填写中英文数字以及@符号'
      }
    },
    data () {
      let editorValues = this.value.values
      return {
        editorValues,
        DEFAULT_ITEMS,
        newDialogState: !1,
        activeName: '',
        rules: {},
        msgTitle: '新增填写项',
        validatorObj: {},
        form: {
          fieldText: '',
          listItems: [''],
          fieldValues: ['']
        }
      }
    },
    methods: {
      _defaultValue () {
        this.$curIndex = -1
        if (!this.editorValues) {
          this.editorValues = []
        }
        this._updateValue()
      },
      _setValue (data) {
        if (this.$curIndex === -1) {
          this.editorValues.push(data)
        } else {
          this.$set(this.editorValues, this.$curIndex, data)
        }
        this._updateValue()
      },
      _updateValue () {
        let editorValues = this.editorValues
        let updateData = {
          name: 'matchSignupFieldList',
          nameText: '报名填写项'
        }
        // 处理values 保证数据同步
        let newValues = editorValues.map(k => {
          let fieldValues = ''
          // 编辑初始化时 直接使用JSON字符串
          if (k.fieldValues) {
            fieldValues = typeof k.fieldValues === 'string' ? k.fieldValues : JSON.stringify(k.fieldValues)
          } else {
            fieldValues = ''
          }
          return {
            fieldValues,
            fieldText: k.fieldText,
            fieldType: k.fieldType
          }
        })
        updateData.values = [JSON.stringify(newValues)]
        this.$emit('input', {
          values: this.editorValues,
          result: updateData
        })
      },
      handleEditValues (item, index) {
        let listItems
        this.$curIndex = index
        this.form.fieldText = item.fieldText
        if (!item.fieldValues) {
          listItems = [''] // 无值 初始化
        } else {
          listItems = typeof item.fieldValues === 'string' ? JSON.parse(item.fieldValues) : item.fieldValues
          listItems = listItems.map(k => k.text) // 转化
          this.activeName = '1'
        }
        this.form.listItems = listItems
        this.toggleShowDialog('edit')
      },
      handleDelValue (index) {
        this.editorValues.splice(index, 1)
        this._updateValue()
      },
      handleSave () {
        // 新增选项
        this.validate(() => {
          let data = {}
          let formData = this.form
          data.key = this.unique()
          data.fieldText = formData.fieldText
          data.fieldValues = formData.listItems.filter(k => k.trim())
          data.fieldValues = !data.fieldValues.length ? '' : data.fieldValues.map(k => {
            return {text: k}
          }) // 封装对象
          data.fieldType = data.fieldValues.length ? 2 : 1 // 有长度则有选项 则为2
          this._setValue(data)
          this.toggleShowDialog()
        })
      },
      toggleShowDialog (type) {
        if (type === 'add' && this.addBtnDisabled) {
          return false
        }
        this.newDialogState = !this.newDialogState
        this.msgTitle = type === 'edit' ? '编辑填写项' : '新增填写项'
      },
      resetFormData () {
        // 初始化
        this.$nextTick(() => {
          this.form.fieldText = ''
          this.form.listItems = ['']
          this.resetForm()
          this.activeName = '' // 候选项展开状态 初始化
          this.$curIndex = -1 // 初始化索引
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .checkbox-text{
    display: inline-block;
    width:140px;
  }
  .match-form-item{
    .btn-match-wrapper{
      position: relative;
      .el-button{
        width:100%;
        margin-bottom:20px;
      }
      .match-delete-icon{
        position: absolute;
        right: 0;
        top: -11px;
        z-index: 1;
        padding: 5px;
        font-size: 16px;
        cursor: pointer;
        color: #ccc;
        &:before{
          background-color: #fff;
        }
        &:hover{
          color: #ff4949;
        }
      }
    }
  }
</style>
<style lang="scss">
  .match-form-item{
    .el-form-item__content{
      margin-left: 0 !important;
    }
    .match-dialog-wrapper{
      .el-dialog__body{
        .el-collapse{
          text-align: left;
          border: none;
          .el-collapse-item__header{
            margin-top: 30px;
            color: #3983e5;
            height: 20px;
            line-height: 20px;
            border: none;
            padding-left: 0;
          }
          .el-collapse-item__wrap{
            border: none;
            background-color: transparent;
            .el-collapse-item__content{
              padding: 0 15px 0 0;
              .tips{
                padding-left: 21px;
                font-size: 14px;
                color: #999;
              }
            }
          }
        }
      }
    }
    
  }
</style>
